﻿Imports System.Data.SqlClient
Imports System.Diagnostics
'Imports System.Windows.Forms


Public Class Explorer1
    Dim common_conn As New common
    Dim NewConString = ConnectDatabase.GetRegistryValue("stringcon")
    Dim ANTS As Control

    Private Sub Explorer1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Set up the UI
        Dim checkc
        checkc = common_conn.CheckConnection(NewConString)

        If checkc = "" Then

            MsgBox("Connected to database successfully!")
            SetUpListViewColumns()
            common_conn.Load_trees()

        Else
            MsgBox("Oops!! Seems like the database connection is lost.", MsgBoxStyle.Exclamation)
            If ConnectDatabase.Visible = False Then
                ConnectDatabase.ShowDialog()
            End If
        End If
    End Sub

     Private Sub SetUpListViewColumns()
        'List Column Headers
        ListView.Clear()
        Dim lvColumnHeader As ColumnHeader
        lvColumnHeader = ListView.Columns.Add("#")
        lvColumnHeader.Width = 50
        lvColumnHeader = ListView.Columns.Add("Title")
        lvColumnHeader.Width = 100
        lvColumnHeader = ListView.Columns.Add("Decription")
        lvColumnHeader.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize)
    End Sub

    Public Sub Load_view(ByVal command As String)
        'Load respective data in columns
        Dim conn As New SqlClient.SqlConnection

        conn.ConnectionString = NewConString
        Dim myInsertQuery As String = command

        Dim myCommand As New SqlCommand(myInsertQuery)
        myCommand.Connection = conn

        conn.Open()
        Dim reader As SqlDataReader = myCommand.ExecuteReader()
        Dim lvItem As ListViewItem

        Do
            While reader.Read()

                lvItem = ListView.Items.Add(ListView.Items.Count + 1)
                lvItem.SubItems.AddRange(New String() {reader(1), reader(2)})
                lvItem.ImageIndex = 3

            End While
        Loop While reader.NextResult()

    End Sub 'SelectSqlClientSrvRows


    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub

    Private Sub ToolBarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolBarToolStripMenuItem.Click
        'Toggle the visibility of the toolstrip and also the checked state of the associated menu item
        ToolBarToolStripMenuItem.Checked = Not ToolBarToolStripMenuItem.Checked
        ToolStrip.Visible = ToolBarToolStripMenuItem.Checked
    End Sub

    Private Sub StatusBarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StatusBarToolStripMenuItem.Click
        'Toggle the visibility of the statusstrip and also the checked state of the associated menu item
        StatusBarToolStripMenuItem.Checked = Not StatusBarToolStripMenuItem.Checked
        StatusStrip.Visible = StatusBarToolStripMenuItem.Checked
    End Sub

    'Change whether or not the folders pane is visible
    'Private Sub ToggleFoldersVisible()
    '    'First toggle the checked state of the associated menu item
    '    FoldersToolStripMenuItem.Checked = Not FoldersToolStripMenuItem.Checked

    '    'Change the Folders toolbar button to be in sync
    '    FoldersToolStripButton.Checked = FoldersToolStripMenuItem.Checked

    '    ' Collapse the Panel containing the TreeView.
    '    Me.SplitContainer.Panel1Collapsed = Not FoldersToolStripMenuItem.Checked
    'End Sub

    'Private Sub FoldersToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    ToggleFoldersVisible()
    'End Sub

    'Private Sub FoldersToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    ToggleFoldersVisible()
    'End Sub

    'Private Sub SetView(ByVal View As System.Windows.Forms.View)
    '    'Figure out which menu item should be checked
    '    Dim MenuItemToCheck As ToolStripMenuItem = Nothing
    '    Select Case View
    '        Case View.Details
    '            MenuItemToCheck = DetailsToolStripMenuItem
    '        Case View.LargeIcon
    '            MenuItemToCheck = LargeIconsToolStripMenuItem
    '        Case View.List
    '            MenuItemToCheck = ListToolStripMenuItem
    '        Case View.SmallIcon
    '            MenuItemToCheck = SmallIconsToolStripMenuItem
    '        Case View.Tile
    '            MenuItemToCheck = TileToolStripMenuItem
    '        Case Else
    '            Debug.Fail("Unexpected View")
    '            View = View.Details
    '            MenuItemToCheck = DetailsToolStripMenuItem
    '    End Select

    '    'Check the appropriate menu item and deselect all others under the Views menu
    '    For Each MenuItem As ToolStripMenuItem In ListViewToolStripButton.DropDownItems
    '        If MenuItem Is MenuItemToCheck Then
    '            MenuItem.Checked = True
    '        Else
    '            MenuItem.Checked = False
    '        End If
    '    Next

    '    'Finally, set the view requested
    '    ListView.View = View
    'End Sub

    'Private Sub ListToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    SetView(View.List)
    'End Sub

    'Private Sub DetailsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    SetView(View.Details)
    'End Sub

    'Private Sub LargeIconsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    SetView(View.LargeIcon)
    'End Sub

    'Private Sub SmallIconsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    SetView(View.SmallIcon)
    'End Sub

    'Private Sub TileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    SetView(View.Tile)
    'End Sub

    'Private Sub OpenToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
    '    Dim OpenFileDialog As New OpenFileDialog
    '    OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
    '    OpenFileDialog.Filter = "Text Files (*.txt)|*.txt"
    '    OpenFileDialog.ShowDialog(Me)

    '    Dim FileName As String = OpenFileDialog.FileName
    '    ' TODO: Add code to open the file
    'End Sub

    'Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SaveAsToolStripMenuItem.Click
    '    Dim SaveFileDialog As New SaveFileDialog
    '    SaveFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
    '    SaveFileDialog.Filter = "Text Files (*.txt)|*.txt"
    '    SaveFileDialog.ShowDialog(Me)

    '    Dim FileName As String = SaveFileDialog.FileName
    '    ' TODO: Add code here to save the current contents of the form to a file.
    'End Sub

    Private Sub TreeView_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView.AfterSelect
        ' TODO: Add code to change the listview contents based on the currently-selected node of the treeview
        ListView.Items.Clear()
        Load_view("SELECT * from tree_views where Node_Level = '" & Add_New_Test_Suite.GetLastId() & "' ORDER BY id")
    End Sub


    Private m_SortingColumn As ColumnHeader


    Private Sub ListView_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs)
        ' Get the new sorting column.  
        Dim new_sorting_column As ColumnHeader = ListView.Columns(e.Column)
        ' Figure out the new sorting order.  
        Dim sort_order As System.Windows.Forms.SortOrder
        If m_SortingColumn Is Nothing Then
            ' New column. Sort ascending.  
            sort_order = SortOrder.Ascending
        Else ' See if this is the same column.  
            If new_sorting_column.Equals(m_SortingColumn) Then
                ' Same column. Switch the sort order.  
                If m_SortingColumn.ImageIndex = 4 Then
                    sort_order = SortOrder.Descending
                Else
                    sort_order = SortOrder.Ascending
                End If
            Else
                ' New column. Sort ascending.  
                sort_order = SortOrder.Ascending
            End If
            ' Remove the old sort indicator.  
            m_SortingColumn.ImageIndex = 6


        End If
        ' Display the new sort order.  
        m_SortingColumn = new_sorting_column
        If sort_order = SortOrder.Ascending Then
            m_SortingColumn.ImageIndex = 4
        Else
            m_SortingColumn.ImageIndex = 5
        End If
        ' Create a comparer.  
        ListView.ListViewItemSorter = New clsListviewSorter(e.Column, sort_order)
        ' Sort.  
        ListView.Sort()
    End Sub

   
    Private Sub Refresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Refresh.Click
        TreeView.Nodes.Clear()
        SetUpListViewColumns()
        common_conn.Load_trees()
        TreeView.SelectedNode = TreeView.TopNode
        TreeView.SelectedNode.Expand()
    End Sub

    Private Sub TreeView1_NodeMouseClick1(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles TreeView.NodeMouseClick
        If (e.Button = MouseButtons.Right) Then
            TreeView.SelectedNode = e.Node
        End If
    End Sub

    Private Sub NodeContextMenu_Opening(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles NodeContextMenu.Opening
        If TreeView.TopNode.IsSelected Then
            Item6_edit.Enabled = False
            Item7_delete.Enabled = False
        Else
            Item7_delete.Enabled = True
            Item6_edit.Enabled = True
        End If
    End Sub

    Private Sub Item3_ANTS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Item3_ANTS.Click
        Add_New_Test_Suite.ShowDialog()
        Add_New_Test_Suite.TST_Text.Text = ""
        Add_New_Test_Suite.TSD_Text.Text = ""
    End Sub

    Private Sub Item1_expand_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Item1_expand.Click
        TreeView.SelectedNode.Expand()
    End Sub

    Private Sub Item7_delete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Item7_delete.Click
        ' Removes currently selected node
        Dim getparentnodetoselect, getdeletednode, getdeletednodeID
        getparentnodetoselect = TreeView.SelectedNode.Parent
        getdeletednode = TreeView.SelectedNode.Text
        'MsgBox("To be deleted: " & getdeletednode)
        'MsgBox("ID of deleted node: " & GetIdofnode(getdeletednode))
        getdeletednodeID = GetIdofnode(getdeletednode)
        'MsgBox("Baap of deleted node: " & getparentnodetoselect.text)
        Dim response As MsgBoxResult
        response = MsgBox("Are you sure you want to delete? All data under this node will be lost.", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Deleting " & TreeView.SelectedNode.Text)
        If response = MsgBoxResult.Yes Then
            Add_New_Test_Suite.Execute_commands("DELETE FROM Tree_Views WHERE Id = '" & getdeletednodeID & "'")
            Add_New_Test_Suite.Execute_commands("DELETE FROM Tree_Views WHERE Node_Level = '" & getdeletednodeID & "'")
            common_conn.Load_trees()
            TreeView.ExpandAll()
            TreeView.SelectedNode = getparentnodetoselect
        ElseIf response = MsgBoxResult.No Then
            Exit Sub
        End If
    End Sub

    Public Function GetIdofnode(ByVal nodename As String)

        Dim conn As New SqlClient.SqlConnection
        ' todo: modify the connection string and include any
        ' additional required properties for your database.
        conn.ConnectionString = NewConString
        Dim myinsertquery As String = ("select Id from Tree_Views where Node_Title = '" & nodename & "'")
        Dim mycommand As New SqlCommand(myinsertquery)
        mycommand.Connection = conn
        conn.Open()
        Dim reader As SqlDataReader = mycommand.ExecuteReader()
        While reader.Read()
            GetIdofnode = (reader(0).ToString)
        End While

    End Function


    Private Sub TabControl1_Selecting(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl1.Selecting

        Dim messageBoxVB As New System.Text.StringBuilder()
        messageBoxVB.AppendFormat("{0} = {1}", "TabPage", e.TabPage)
        messageBoxVB.AppendLine()
        messageBoxVB.AppendFormat("{0} = {1}", "TabPageIndex", e.TabPageIndex)
        messageBoxVB.AppendLine()
        messageBoxVB.AppendFormat("{0} = {1}", "Action", e.Action)
        messageBoxVB.AppendLine()
        messageBoxVB.AppendFormat("{0} = {1}", "Cancel", e.Cancel)
        messageBoxVB.AppendLine()
        MessageBox.Show(messageBoxVB.ToString(), "Selecting Event")
    End Sub
End Class
